package ws.jdbc.concurrent.driver.sqlserver

import java.sql.*

/**
 *
 * @author Wilson Santos, <wilson.santos@ua.pt>
 */
class PrimaryKeyTest extends GroovyTestCase {
  /** URL to connect to the SQL Server. */
  String url = "jdbc:sqlserver://localhost:1433;username=sa;password=sg4765j;database=JDBCDriverTests"
  /** Connection with the SQL Server. */
  Connection con
  /** Object used on the tests. */
  ResultSet rs
  /** SQL query to create the result set. */
  String sqlQuery = "Select * from Std_Student"
  /** Number of created threads during the cursor tests. */
  def nthreads = 20
  def stmt
  def rand = new Random()

  PrimaryKeyTest() {
    con = DriverManager.getConnection(url)
  }

  void test1() {
    deleteTestData()
    createTestData(5)

    Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)
    ResultSet rs = st.executeQuery(sqlQuery)
    

    while(rs.next()) {
      println rs.getInt(1) + ' ' + rs.getString(2)
    }

//    println rs.tdsResultSet
    
    rs.absolute(3)
    rs.updateInt(1, 111)
    rs.updateString(2, "111")
    rs.updateRow()

//    rs.refreshRow()

//    println rs.tdsResultSet

    println "-------------------------------------"
//    rs.beforeFirst()
    rs.absolute(1)
    while(rs.next()) {
      println rs.getInt(1) + ' ' + rs.getString(2) + ' ' + rs.getString(3)
    }

    rs.close()
    st.close()
    con.close()
  }

  void deleteTestData() {
    Statement stmt = con.createStatement();
    stmt.executeUpdate("DELETE FROM Std_Student")
    stmt.close()
  }

  void createTestData(int rowCount) throws SQLException {
    Statement stmt = con.createStatement();
    for (int i = 0; i < rowCount; ++i) {
      String batch = new String("INSERT INTO Std_Student"
              + " VALUES("
              + i
              + ", 'StdF " + i + "'"
              + ", 'StdL " + i + "'"
              + ", " + i
              + ", " + 16.0
              + ", " + i
              + ", " + i
              + ", 'std" + i + "@mail.com'"
              + ")");
      stmt.addBatch(batch);
    }
    stmt.executeBatch();
    stmt.close()
  }
}

